/*
 * @description: 错误边界组件
 * @Date: 2021-11-12 14:47:52
 * @author: thurs
 * @LastEditors: thurs
 * @LastEditTime: 2021-11-15 10:17:01
 * @demand: 处理错误边界
 */
import { Component, PropsWithChildren, ReactElement } from "react";
import styled from "styled-components";

export class ErrorBoundary extends Component<PropsWithChildren<{ fallbackRender?: ((props: { error: Error | null }) => ReactElement) }>, { error: Error | null }> {
  state = { error: null };
  static getDerivedStateFromError(error: Error) {
    return { error };
  }
  render() {
    const { error } = this.state;
    const { children, fallbackRender } = this.props;

    if (error) {
      return fallbackRender ? fallbackRender(error) : (<FullPage>{(error as Error).message}</FullPage>);
    }
    return children;
  }
}

const FullPage = styled.div`
  display: flex;
  justify-content: center;
  height: 100vh;
  line-height: 100vh;
  text-align: center;
  color: red;
  font-weight: bold;
`;